import { Component, Vue } from 'vue-property-decorator'
import styles from '../NewApply/NewApply.less'
import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import SealDetail from './SealDetail'
// import RevokeSeal from "../RevokeApply/RevokeSeal";
import LossSeal from '../LossApply/LossSeal'
import TipsDialog from '@/components/TipsDialog'
import OperationCol from '@/components/OperationCol'
import SealStatus, { issueList } from '@/components/SealStatus'
import {
  orgLicenseTypes,
  orgTypes,
  userLicenseTypes,
  adminTypes,
  useTypes,
  formatStatus,
  sealTypes,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { UserState } from '../../store/modules/user'
import { Table } from 'element-ui'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class AppliedForMe extends Vue {
  @State((state: RootState) => state.appliedForMe.sealList)
  private sealList!: any[]
  @State((state: RootState) => state.appliedForMe.total)
  private total!: number
  @State((state: RootState) => state.appliedForMe.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.revokeApply.revokeVisible)
  private revokeVisible!: boolean
  @State((state: RootState) => state.revokeApply.isEdit)
  private isEdit!: boolean
  @State((state: RootState) => state.revokeApply.title)
  private revokeTitle!: boolean
  @State((state: RootState) => state.lossApply.title)
  private lossTitle!: boolean
  @State((state: RootState) => state.lossApply.isEdit)
  private isLossEdit!: boolean
  @State((state: RootState) => state.lossApply.isLoss)
  private isLoss!: boolean
  @State((state: RootState) => state.lossApply.lossVisible)
  private lossVisible!: boolean
  @State((state: RootState) => state.appliedForMe.loading)
  private loading!: boolean
  @State((state: RootState) => state.appliedForMe.sealData)
  private sealData?: any
  @State((state: RootState) => state.user)
  private user!: UserState
  @State((state: RootState) => state.revokeApply.saveLoading)
  private revokeLoading!: boolean
  @State((state: RootState) => state.lossApply.saveLoading)
  private lossLoading!: boolean
  // @State((state: RootState) => state.updateApply.updateVisible)
  // private updateVisible!: boolean;
  // @State((state: RootState) => state.updateApply.title)
  // private updateTitle!: boolean;
  // @State((state: RootState) => state.updateApply.saveLoading)
  // private updateLoading!: boolean;
  // @State((state: RootState) => state.updateApply.auditOrgList)
  private auditOrgList!: boolean
  @State((state: RootState) => state.lossApply.content)
  private lossContent!: boolean

  private sealType: number[] = []
  private status: number[] = []
  private sealName: string = ''
  private pageIndex: number = 1
  private pageSize: number = 10
  private sealOption: any[] = []
  private showTimeline: boolean = false
  private tipsVisible: boolean = false
  private sealApplyId = 0
  private sealApplyType = 0
  private sealRecordId = ''
  private tipsContent = ''

  @Mutation('appliedForMe/setStateData') private setStateData!: any
  @Mutation('revokeApply/setStateData') private setRevokeStateData!: any
  @Mutation('lossApply/setStateData') private setLossStateData!: any
  // @Mutation("updateApply/setStateData") private setUpdateStateData!: any;
  @Action('appliedForMe/getList') private getList!: any
  @Action('appliedForMe/sealDetail') private sealDetail!: any
  @Action('revokeApply/saveSeal') private saveSeal!: any
  @Action('revokeApply/saveAndSubmit') private saveAndSubmit!: any
  @Action('revokeApply/revokeApplyCheck') private revokeApplyCheck!: any
  @Action('lossApply/lossSealApply') private lossSealApply!: any
  @Action('recoverApply/recoverSealApply') private recoverSealApply!: any
  @Action('reissueApply/reissueApply') private reissueApply!: any

  protected render() {
    return (
      <div class="p10">
        <div class={{ [styles.query]: true, custom: true }}>
          <span class={styles.part}>
            <span>印章类别</span>
            <el-select
              v-model={this.sealType}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {sealTypes.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.id}
                  label={sealType.value}
                  value={sealType.id}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>印章状态</span>
            <el-select
              v-model={this.status}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {issueList.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.key}
                  label={sealType.text}
                  value={sealType.key}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>印章名称</span>
            <el-input v-model={this.sealName} />
          </span>
          <span class={styles.part}>
            <el-button
              plain
              class="min color-blue"
              loading={this.loading}
              onClick={this.query}
            >
              搜索
            </el-button>
            <el-button plain class="min color-gray" onClick={this.reset}>
              重置
            </el-button>
          </span>
        </div>
        <el-table
          data={this.sealList}
          style="width: 100%"
          v-loading={this.loading}
          ref="table"
        >
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg="当前查询条件下暂无印章数据"
            url={require('@/assets/seal-empty.svg')}
          >
            <el-button onClick={this.toApplyPage}>前往申请印章</el-button>
            <el-button type="primary" onClick={this.toNewApply}>
              前往查看申请记录
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="sealCode"
            label="印章编码"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealName"
            label="印章名称"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="name"
            label="印章图片"
            min-width="100"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <img
                      src={scope.row.sealPicUrl}
                      height="25"
                      alt="印章图片"
                    />
                  )
                },
              },
            }}
          />
          <el-table-column
            prop="sealType"
            label="印章类别"
            min-width="80"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return formatStatus(sealTypes, scope.row.sealType)
                },
              },
            }}
          />
          <el-table-column
            prop="startTime"
            label="启用时间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="endTime"
            label="终止时间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealStatus"
            label="状态"
            min-width="100"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return <SealStatus issue status={scope.row.sealStatus} />
                },
              },
            }}
          />

          <el-table-column
            prop="id"
            label="操作"
            width="200"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <span>
                      <OperationCol
                        operations={this.filterOptions(
                          scope.row.sealStatus,
                          scope.row.sealApplyType
                        )}
                        showNum={4}
                        row={scope.row}
                        index={scope.$index}
                      />
                    </span>
                  )
                },
              },
            }}
          />
        </el-table>
        {this.sealList && this.sealList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
          />
        )}
        <SealDetail
          onVisibleChange={(val: boolean) => {
            this.setStateData({ detailVisible: val })
          }}
          data={this.sealData}
          visible={this.detailVisible}
        />
        {/* <RevokeSeal
					onVisibleChange={(val: boolean) => {
						this.setRevokeStateData({ revokeVisible: val });
					}}
					title={this.revokeTitle}
					showTimeline={this.showTimeline}
					saveLoading={this.revokeLoading}
					uploadUrl={uploadUrl}
					data={this.sealData}
					onSave={this.save}
					isEdit={this.isEdit}
					onSaveAndSubmit={this.saveSubmit}
					onChange={(val: boolean) => {
						this.setRevokeStateData({ revokeVisible: val });
					}}
					sealOption={this.sealOption}
					visible={this.revokeVisible}
				/> */}
        <LossSeal
          onVisibleChange={(val: boolean) => {
            this.setLossStateData({ lossVisible: val })
          }}
          title={this.lossTitle}
          isEdit={this.isLossEdit}
          isLoss={this.isLoss}
          data={this.sealData}
          showSubmit
          saveLoading={this.lossLoading}
          onSave={this.lossOrRecover}
          visible={this.lossVisible}
          content={this.lossContent}
        />
        <TipsDialog
          onVisibleChange={(val: boolean) => {
            this.tipsVisible = val
          }}
          visible={this.tipsVisible}
          title="提示"
          btns={['关闭', '点击前往']}
          onConfirm={this.gotoRevokeDetail}
          content={this.tipsContent}
        />
        {/* <UpdateSeal
					onVisibleChange={(e: boolean) => {
						this.setUpdateStateData({ updateVisible: e });
					}}
					showTimeline={false}
					visible={this.updateVisible}
					defaultData={this.sealData}
					saveLoading={this.updateLoading}
					title={this.updateTitle}
					showOption={true}
					sealOption={this.sealOption}
					uploadUrl={uploadUrl}
					auditOrgList={this.auditOrgList}
					queryAuditOrg={this.queryAuditOrg}
					onCreateForm={this.createApplyForm}
					onSave={this.saveUpdate}
					onSaveAndSubmit={this.saveSubmitUpdate}
				/> */}
      </div>
    )
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
      {
        id: 2,
        text: '补发',
        onClick: (index: number, rows: any) => {
          this.openReissue(rows)
        },
      },
      {
        id: 3,
        text: '吊销',
        onClick: (index: number, rows: any) => {
          this.openRevoke(rows)
        },
      },
      {
        id: 4,
        text: '挂失',
        onClick: (index: number, rows: any) => {
          this.openLoss(rows)
        },
      },
      {
        id: 5,
        text: '恢复',
        onClick: (index: number, rows: any) => {
          this.openRecover(rows)
        },
      },
      {
        id: 6,
        text: '延期',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
    ]

    return btns
  }

  get agentInfo() {
    return {
      agentName: this.user.accountName,
      agentId: this.user.accountUUID,
      agentMobile: this.user.accountMobile,
      agentLicenseType: this.user.accountLicenseType,
      agentLicenseNumber: this.user.accountLicenseNumber,
      agentMobileDes: desensitization(this.user.accountMobile),
      agentLicenseNumberDes: desensitization(this.user.accountLicenseNumber),
      agentLicenseTypeName: formatStatus(
        userLicenseTypes,
        this.user.accountLicenseType
      ),
    }
  }

  private mounted() {
    this.query()
  }
  private filterOptions(status: number, sealApplyType: number) {
    if (status === 1) {
      // 已发布
      return this.getOperations.filter(
        (item: any) =>
          item.id === 1 ||
          item.id === 4 ||
          (item.id === 3 && (sealApplyType === 0 || sealApplyType === 2))
      )
    } else if (status === 2) {
      // 已挂失
      return this.getOperations.filter(
        (item: any) =>
          item.id === 1 ||
          (item.id === 2 && (sealApplyType === 0 || sealApplyType === 6)) ||
          (item.id === 5 && sealApplyType !== 6) ||
          (item.id === 3 && (sealApplyType === 0 || sealApplyType === 2))
      )
    } else if (status === 3) {
      // 已吊销
      return this.getOperations.filter((item: any) => item.id === 1)
    } else if (status === 4) {
      // 已过期
      return this.getOperations.filter(
        (item: any) => item.id === 1 || item.id === 6
      )
    }
  }

  private detail(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.setStateData({
        detailVisible: true,
        sealData: Object.assign({}, data, {
          organizeType: formatStatus(orgTypes, data.organizeType),
          organizeCardType: formatStatus(
            orgLicenseTypes,
            data.organizeCardType
          ),
          organizeLevel: formatStatus(adminTypes, data.organizeLevel),
          inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
          inspectMobileDes: desensitization(data.inspectMobile),
          inspectCardIdDes: desensitization(data.inspectCardId),
        }),
      })
      this.setStateData({ detailVisible: true })
    })
  }

  toApplyPage() {
    this.$router.push({ name: 'applyPage', params: { type: 'newApply' } })
  }

  toNewApply() {
    this.$router.push({ name: 'newApply' })
  }

  private query() {
    this.pageIndex = 1
    this.queryList()
  }
  private async queryList() {
    await this.getList(this)
    const table = this.$refs.table as Table
    table.doLayout()
  }

  private handleSizeChange(val: number) {
    this.pageSize = val
    this.query()
  }

  private handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  private reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.query()
  }

  private gotoRevokeDetail() {
    const path =
      this.sealApplyType === 2 ? '/home/revokeApply' : '/home/reissueApply'
    this.$router.push({
      path: path,
      query: { id: this.sealApplyId.toString(), recordId: this.sealRecordId },
    })
  }

  private async openRevoke(row: any) {
    const { sealApplyId, sealApplyRecordId, sealApplyType } = row
    this.sealApplyId = sealApplyId
    this.sealRecordId = sealApplyRecordId
    this.sealApplyType = sealApplyType
    if (sealApplyId !== 0) {
      // 获取已提交的吊销申请
      this.tipsContent = '当前印章已提交过吊销申请。'
      this.tipsVisible = true
    } else {
      this.$router.push({
        name: 'applyPage',
        params: { type: 'revokeApply' },
        query: { sealSn: row.sealSn },
      })
      // this.sealDetail(row.sealSn).then((data: any) => {
      // 	this.setStateData({
      // 		sealData: Object.assign(
      // 			{},
      // 			data,
      // 			{
      // 				organizeType: formatStatus(orgTypes, data.organizeType),
      // 				organizeCardType: formatStatus(orgLicenseTypes, data.organizeCardType),
      // 				organizeLevel: formatStatus(adminTypes, data.organizeLevel),
      // 				inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
      // 				sealType: formatStatus(sealTypes, data.sealType),
      // 				sealUseType: formatStatus(useTypes, data.sealUseType),
      // 				inspectMobileDes: desensitization(data.inspectMobile),
      // 				inspectCardIdDes: desensitization(data.inspectCardId),
      // 				agentLicenseTypeName: formatStatus(userLicenseTypes, this.user.accountLicenseType)
      // 			},
      // 			this.agentInfo
      // 		)
      // 	});
      // 	this.showTimeline = false;
      // 	this.setRevokeStateData({ revokeVisible: true, isEdit: true, title: "吊销印章申请" });
      // });
    }
  }

  private openLoss(row: any) {
    this.$router.push({
      name: 'applyPage',
      params: { type: 'lossApply' },
      query: { sealSn: row.sealSn },
    })
    // this.sealDetail(row.sealSn).then((data: any) => {
    // 	this.setStateData({
    // 		sealData: Object.assign(
    // 			{},
    // 			data,
    // 			{
    // 				organizeType: formatStatus(orgTypes, data.organizeType),
    // 				organizeCardType: formatStatus(orgLicenseTypes, data.organizeCardType),
    // 				organizeLevel: formatStatus(adminTypes, data.organizeLevel),
    // 				inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
    // 				sealType: formatStatus(sealTypes, data.sealType),
    // 				sealUseType: formatStatus(useTypes, data.sealUseType),
    // 				inspectMobileDes: desensitization(data.inspectMobile),
    // 				inspectCardIdDes: desensitization(data.inspectCardId)
    // 			},
    // 			this.agentInfo
    // 		)
    // 	});
    // 	this.setLossStateData({
    // 		lossVisible: true,
    // 		isEdit: true,
    // 		isLoss: true,
    // 		title: "挂失印章申请",
    // 		content: "挂失"
    // 	});
    // });
  }

  private openRecover(row: any) {
    this.sealDetail(row.sealSn).then((data: any) => {
      this.setStateData({
        sealData: Object.assign(
          {},
          data,
          {
            organizeType: formatStatus(orgTypes, data.organizeType),
            organizeCardType: formatStatus(
              orgLicenseTypes,
              data.organizeCardType
            ),
            organizeLevel: formatStatus(adminTypes, data.organizeLevel),
            inspectCardType: formatStatus(
              userLicenseTypes,
              data.inspectCardType
            ),
            sealType: formatStatus(sealTypes, data.sealType),
            sealUseType: formatStatus(useTypes, data.sealUseType),
            inspectMobileDes: desensitization(data.inspectMobile),
            inspectCardIdDes: desensitization(data.inspectCardId),
          },
          this.agentInfo
        ),
      })
      this.setLossStateData({
        lossVisible: true,
        isEdit: false,
        isLoss: false,
        title: '印章挂失恢复申请',
        content: '挂失',
      })
    })
  }

  private openReissue(row: any) {
    const { sealApplyId, sealApplyRecordId, sealApplyType } = row
    this.sealApplyId = sealApplyId
    this.sealRecordId = sealApplyRecordId
    this.sealApplyType = sealApplyType
    if (sealApplyId !== 0) {
      // 获取已提交的补发申请
      this.tipsContent = '当前印章已提交过补发申请。'
      this.tipsVisible = true
    } else {
      this.$router.push({
        name: 'applyPage',
        params: { type: 'reissueApply' },
        query: { sealSn: row.sealSn },
      })
      // this.sealDetail(row.sealSn).then((data: any) => {
      // 	this.setStateData({
      // 		sealData: Object.assign(
      // 			{},
      // 			data,
      // 			{
      // 				organizeType: formatStatus(orgTypes, data.organizeType),
      // 				organizeCardType: formatStatus(orgLicenseTypes, data.organizeCardType),
      // 				organizeLevel: formatStatus(adminTypes, data.organizeLevel),
      // 				inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
      // 				sealType: formatStatus(sealTypes, data.sealType),
      // 				sealUseType: formatStatus(useTypes, data.sealUseType),
      // 				inspectMobileDes: desensitization(data.inspectMobile),
      // 				inspectCardIdDes: desensitization(data.inspectCardId)
      // 			},
      // 			this.agentInfo
      // 		)
      // 	});
      // 	this.setLossStateData({
      // 		lossVisible: true,
      // 		isEdit: true,
      // 		isLoss: true,
      // 		title: "印章补发申请",
      // 		content: "补发"
      // 	});
      // });
    }
  }

  private save(data: any) {
    this.setRevokeStateData({ saveLoading: true })
    this.saveSeal(data)
      .then((res: any) => {
        this.setRevokeStateData({ saveLoading: false, revokeVisible: false })
        this.query()
      })
      .catch((e: any) => {
        this.setRevokeStateData({ saveLoading: false })
      })
  }

  private saveSubmit(data: any) {
    this.setRevokeStateData({ saveLoading: true })
    this.saveAndSubmit(data)
      .then((res: any) => {
        this.setRevokeStateData({ saveLoading: false, revokeVisible: false })
        this.query()
      })
      .catch((e: any) => {
        this.setRevokeStateData({ saveLoading: false })
      })
  }

  lossOrRecover(data: { isLoss: boolean; seal: any; isReissue: boolean }) {
    this.setLossStateData({ saveLoading: true })
    if (data.isReissue) {
      // 补发申请
      this.reissueApply({
        sealSn: data.seal.sealSn,
        applyReason: data.seal.reason,
      })
        .then((res: any) => {
          this.$message.success('补发申请已提交')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })

      return
    }
    if (data.isLoss) {
      // 挂失
      this.lossSealApply({
        sealSn: data.seal.sealSn,
        applyReason: data.seal.reason,
      })
        .then((res: any) => {
          this.$message.success('挂失成功')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })
    } else {
      // 恢复
      this.recoverSealApply(data.seal.sealSn)
        .then((res: any) => {
          this.$message.success('恢复成功')
          this.setLossStateData({ saveLoading: false, lossVisible: false })
          this.query()
        })
        .catch((e: any) => {
          this.setLossStateData({ saveLoading: false })
        })
    }
  }

  private createApplyForm(sealData: any) {
    sessionStorage.setItem(
      'updateInfo',
      JSON.stringify({
        organize: sealData.organizeName,
        orgType: formatStatus(orgTypes, sealData.organizeType),
        licenseType: formatStatus(orgLicenseTypes, sealData.organizeCardType),
        licenseNumber: sealData.organizeCardId,
        agentName: sealData.agentName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          sealData.agentLicenseType
        ),
        agentLicenseNumber: sealData.agentLicenseNumber,
        agentMobile: sealData.agentMobile,
        sealName: sealData.sealName,
        newSealName: sealData.newSealName,
        useType: formatStatus(useTypes, sealData.sealUseType),
        sealType: formatStatus(sealTypes, sealData.sealType),
        auditOrg: sealData.auditOrganizeName,
        sealImg: sealData.sealPicUrl,
      })
    )
    window.open(`${window.location.origin}/updateForm`, '_blank')
  }

  // private saveUpdate(data: any) {
  // 	this.setUpdateStateData({ saveLoading: true });
  // 	this.saveUpdateSeal(data)
  // 		.then((res: any) => {
  // 			this.setUpdateStateData({ saveLoading: false, updateVisible: false });
  // 			this.query();
  // 		})
  // 		.catch((e: any) => {
  // 			this.setUpdateStateData({ saveLoading: false });
  // 		});
  // }

  // private saveSubmitUpdate(data: any) {
  // 	this.setUpdateStateData({ saveLoading: true });
  // 	this.saveAndSubmitUpdate(data)
  // 		.then((res: any) => {
  // 			this.setUpdateStateData({ saveLoading: false, updateVisible: false });
  // 			this.query();
  // 		})
  // 		.catch((e: any) => {
  // 			this.setUpdateStateData({ saveLoading: false });
  // 		});
  // }
}
